package cn.donting.jme.expansion.attribute.lmpl;

import cn.donting.jme.expansion.attribute.Attribute;
import org.jdesktop.swingx.HorizontalLayout;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import java.awt.*;

public abstract class AbsMuiltLineAttribute<T, Input extends JComponent> extends Attribute<T> {

    private JPanel rootPanel;
    private JPanel titlePanel;
    private JLabel titleLabel;
    private JCheckBox enable;
    protected Input inputComponent;

    public AbsMuiltLineAttribute(Input component) {
        this.inputComponent = component;
        rootPanel = new JPanel(new VerticalLayout());
        titlePanel = new JPanel(new HorizontalLayout());
        titleLabel = new JLabel();
        titlePanel.add(titleLabel);
        rootPanel.add(titlePanel);
        rootPanel.add(component);
    }

    @Override
    public Container getUIContainer() {
        return rootPanel;
    }

    @Override
    public void setTitle(String title) {
        titleLabel.setText(title);
    }

    @Override
    public String getTitle() {
        return titleLabel.getText();
    }

    @Override
    public void setTip(String tip) {
        titleLabel.setToolTipText(tip);
    }

    protected abstract T getInputValue();

    @Override
    public final T getValue() {
        if (this.enable != null && enable.isSelected()) {
            return getInputValue();
        }
        return null;
    }

    public void setEnable(boolean enable){
        if(this.enable!=null){
            this.enable.setSelected(enable);
        }
        inputComponent.setEnabled(enable);
        titleLabel.setEnabled(enable);
    }

    public void showEnableCheckBox(boolean enable) {
        if (!enable) {
            if (this.enable != null) {
                this.titlePanel.remove(this.enable);
            }
            this.enable=null;
            valueChange(getValue());
            return;
        }
        if (this.enable == null) {
            this.enable = new JCheckBox();
            this.titlePanel.add(this.enable, 0);
            this.enable.addChangeListener(this::enableStateChanged);
        }
        valueChange(getValue());
    }

    private void enableStateChanged(ChangeEvent e) {
        inputComponent.setEnabled(enable.isSelected());
        titleLabel.setEnabled(enable.isSelected());
        if (this.enable.isSelected()) {
            valueChange(getValue());
        } else {
            valueChange(null);
        }
    }

//    @Override
//    public void setTitleWight(int wight) {
//
//    }
}
